import axios from 'axios';
import {loginRouterName, notFoundRouterName, serverErrorRouterName} from "@/router/routes.js";
import {useUserStore} from "@/store/sys/user.js";
import router from "@/router/index.js";

const httpRequest = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    }
})

// 添加请求拦截器
httpRequest.interceptors.request.use(function (config) {
    const userStore = useUserStore()
    if (userStore.isLogin) {
        config.headers[userStore.getTokenName] = userStore.getTokenValue
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    window.$message.error(`~~${error.status}~~`)
    return Promise.reject(error);
});

// 添加响应拦截器
httpRequest.interceptors.response.use(async (response) => {
    if (response.config.responseType === 'blob') {
        // 说明是文件下载
        return response
    }
    const {code, msg} = response.data
    if (code === 0) {
        return response.data
    } else {
        window.$message.error(msg)
    }
    return response;
}, async function (error) {
    if (error.name === 'CanceledError') {
        return
    }
    const {response, config} = error
    if (response.status === 500) {
        window.$message.error('~~服务器异常~~')
        await router.push({name: serverErrorRouterName})
    } else if (response.status === 401) {
        window.$message.error('~~登录过期，请重新登录~~')
        await router.push({name: loginRouterName, replace: true});
    } else if (response.status === 403) {
        window.$message.error(`${config.url} - 权限不足`)
    } else if (response.status === 404) {
        window.$message.error(`~~访问的资源【${config.url}】不存在~~`)
        await router.push({name: notFoundRouterName})
    } else {
        window.$message.error(`~~${response.status}~~`)
    }
    return Promise.reject(error);
});

/**
 * 文件下载
 * @param filename
 * @param url
 * @param config
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
httpRequest.download = async (filename, url, config) => {
    try {
        const response = await httpRequest.get(url, {
            responseType: 'blob',
            ...config
        })
        // 创建一个 Blob 对象
        const blob = new Blob([response.data]);
        // 创建一个指向 Blob 对象的 URL
        const downloadUrl = window.URL.createObjectURL(blob);
        // 创建一个隐藏的 a 元素用于下载
        const link = document.createElement('a');
        link.href = downloadUrl;
        const filenameIndex = filename.lastIndexOf('.')
        const suffix = filename.substring(filenameIndex)
        const prefix = filename.substring(0, filenameIndex)
        link.download = `${prefix}-${new Date().getTime()}${suffix}`;
        document.body.appendChild(link);
        link.click();
        // 移除 a 元素
        document.body.removeChild(link);
        // 释放 URL 对象
        window.URL.revokeObjectURL(downloadUrl);
    } catch (err) {
        console.error('Error downloading the file', err);
    }
}

export default httpRequest;